<script lang="ts" setup>
  import appStore from '@/store'
  import { onMounted, reactive, ref, watch } from 'vue'
  import autoScaling from '@/api/autoScaling'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules, Action } from 'element-plus'
  import { useRouter, useRoute } from 'vue-router'
  import { useI18n } from 'vue-i18n'
  const { t } = useI18n()
  const router = useRouter()
  const route = useRoute()
  let asData = reactive({
    data: {
      name: '',
      policy_type: '',
      target_based_configuration: {
        metric_name: '',
        min_target_value: 1,
        max_target_value: 100
      }
    }
  })
  let autoScalingValue = ref('')
  const autoScalingRef = ref<FormInstance>()
  const minMax = (rule: any, value: any, callback: any) => {
    if (asData.data.target_based_configuration.max_target_value) {
      if (value <= asData.data.target_based_configuration.max_target_value) {
        callback()
      } else {
        callback(new Error('最小目标可用会话比要小于最大目标可用会话比'))
      }
    } else if (!value) {
      callback()
    } else {
      callback(new Error('请填写最大目标可用会话比'))
    }
  }
  const maax = (rule: any, value: any, callback: any) => {
    if (asData.data.target_based_configuration.max_target_value) {
      callback()
    } else if (!value) {
      callback()
    } else {
      callback(new Error('请填写最小目标可用会话比'))
    }
  }
  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    policy_type: [{ required: true, message: '请选择策略类型', trigger: 'change' }],
    'target_based_configuration.metric_name': [{ required: true, message: '请选择指标名称', trigger: 'change' }],
    'target_based_configuration.max_target_value': [
      { required: true, type: 'number', min: 1, message: '请输入大于0的数字', trigger: ['change', 'blur'] },
      {
        validator: maax,
        trigger: ['change', 'blur']
      }
    ],
    'target_based_configuration.min_target_value': [
      { required: true, type: 'number', min: 1, message: '请输入大于0的数字', trigger: ['change', 'blur'] },
      {
        validator: minMax,
        trigger: ['change', 'blur']
      }
    ]
  })

  const policy_type_options = [
    {
      value: 'TARGET_BASED',
      label: t('TARGET_BASED')
    }
  ]
  const metric_name_options = [
    {
      value: 'PERCENT_AVAILABLE_SERVER_SESSIONS',
      label: t('PERCENT_AVAILABLE_SERVER_SESSIONS')
    }
  ]

  const param = reactive({
    project_id: appStore.userStore.project_id,
    offset: 0,
    limit: 10,
    autoScaling: {
      name: '',
      fleet_id: '',
      policy_type: '',
      target_based_configuration: {
        metric_name: '',
        min_target_value: 1,
        max_target_value: 100
      }
    }
  })
  const goback = () => {
    router.push({ name: 'autoScaling' })
  }
  let creating = ref(false)
  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (creating.value) return
    if (!formEl) return
    await formEl.validate(async (valid: any, fields: any) => {
      if (valid) {
        param.autoScaling = JSON.parse(JSON.stringify(asData.data))
        try {
          creating.value = true
          let res = await autoScaling.createAutoScaling(param)
          if (res.status < 300) {
            creating.value = false
            ElMessage({
              message: '创建成功',
              type: 'success'
            })
            localStorage.removeItem('asData')
            localStorage.removeItem('fleet_id')
            router.push({ name: 'autoScaling' })
          }
        } catch (err) {
          creating.value = false
          ElMessage.error('创建失败')
        }
      } else {
        ElMessage({
          message: '请检查参数',
          type: 'warning'
        })
      }
    })
  }
  const onReset = () => {
    autoScalingValue.value = ''
    asData.data = {
      name: '',
      policy_type: '',
      target_based_configuration: {
        metric_name: '',
        min_target_value: 1,
        max_target_value: 100
      }
    }
  }
  watch(
    () => asData.data,
    (newValue: any, oldValue: any) => {
      localStorage.setItem('asData', JSON.stringify(newValue))
    },
    { deep: true }
  )
  watch(
    () => autoScalingValue.value,
    (newValue: string, oldValue: any) => {
      localStorage.setItem('asData', newValue)
    }
  )
  onMounted(() => {
    if (localStorage.getItem('asData')) {
      asData.data = JSON.parse(localStorage.getItem('asData') as string)
    }
  })
</script>
<template>
  <div id="createFleet" class="create-index">
    <div class="create-box">
      <span>创建伸缩策略管理</span>
      <span class="back" @click="goback" style="font-size: 14px; margin-left: -11px">&lt;&nbsp;返回</span>
    </div>
    <div class="form-box">
      <el-form ref="autoScalingRef" :model="asData.data" label-width="140px" label-position="left" :inline="true" :rules="rules" class="ac-form">
        <el-form-item prop="name">
          <template #label>
            <div class="item-label">名称</div>
          </template>
          <el-input v-model.trim="asData.data.name" maxlength="1024" placeholder="请输入伸缩策略管理名称" />
        </el-form-item>
        <el-form-item prop="policy_type">
          <template #label>
            <div class="item-label">策略类型</div>
          </template>
          <el-select v-model="asData.data.policy_type" class="m-2" placeholder="请选择策略类型" size="large">
            <el-option v-for="item in policy_type_options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="target_based_configuration.metric_name">
          <template #label>
            <div class="item-label">指标名称</div>
          </template>
          <el-select v-model="asData.data.target_based_configuration.metric_name" class="m-2" placeholder="请选择指标名称" size="large">
            <el-option v-for="item in metric_name_options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="target_based_configuration.min_target_value">
          <template #label>
            <div class="item-label">最小目标可用会话比</div>
          </template>
          <el-input v-model.number="asData.data.target_based_configuration.min_target_value" />
        </el-form-item>
        <el-form-item prop="target_based_configuration.max_target_value">
          <template #label>
            <div class="item-label">最大目标可用会话比</div>
          </template>
          <el-input v-model.number="asData.data.target_based_configuration.max_target_value" />
        </el-form-item>
      </el-form>
      <div class="operateButton">
        <el-button class="btn button" @click="onReset">重置</el-button>
        <el-button class="btn new button" type="primary" @click="onSubmit(autoScalingRef)">创建</el-button>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/create.scss';
  @import '@/assets/scss/dropdownBox.scss';
</style>
